<template>
  <div
    class="echart"
    :id="controlid"
    :style="{
      float: 'left',
      width: '100%',
      height: '250px '
    }"
  ></div>
</template>

<script>
/* eslint-disable */
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
export default {
  methods: {
    initChart() {
      // this.$echarts.registerTheme('tdTheme', tdTheme) // 覆盖默认主题
      this.getchart = echarts.init(document.getElementById(this.controlid))
      this.getchart.setOption(this.options)
      // // 随着屏幕大小调节图表
      window.addEventListener('resize', () => {
        this.resize()
      })
    },
    resize() {
      this.getchart.resize()
    },
    isNumber(val) {
      const regPos = /^\d+(\.\d+)?$/ // 非负浮点数
      const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/ // 负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true
      }
      return false
    },
    setOption() {
      if (this.getchart !== undefined) {
        this.getchart.setOption(this.options, true)
      }
    }
  },
  watch: {
    options: {
      handler(options) {
        // 设置true清空echart缓存
        this.getchart.setOption(options, true)
      },
      deep: true
    }
  },
  data() {
    return { controlid: '', getchart: undefined }
  },
  created() {
    this.controlid =
      'div' + Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
  },
  props: ['options'],
  mounted() {
    const _this = this
    const erd = elementResizeDetectorMaker()
    erd.listenTo(document.getElementById(this.controlid), () => {
      _this.$nextTick(() => {
        _this.resize()
      })
    })

    this.$nextTick(() => {
      this.initChart()
    })
  }
}
</script>
